package com.lym.echo.controller;

import com.lym.echo.entity.Page;
import com.lym.echo.entity.Post;
import com.lym.echo.entity.User;
import com.lym.echo.service.PostService;
import com.lym.echo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 首页
 */
@Controller
public class IndexController {


    @Resource
    private UserService userService;

    @Resource
    private PostService postService;

    @GetMapping("/")
    public String root() {
        return "forward:/index";
    }

    /**
     * 进入首页
     *
     * @param model
     * @param page
     * @param orderMode 默认是 0（最新）
     * @return
     */
    @GetMapping("/index")
    public String getIndexPage(Model model, Page page, @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        //获取总页数
//        page.setRows(postService.findDiscussPostRows(0));
//        page.setPath("/index?orderMode=" + orderMode);

        //分页
        List<Post> list = postService.findPostByPage(0,page.getOffset(),page.getLimit(),orderMode);
        // 封装帖子和该帖子对应的用户信息
        List<Map<String,Object>> posts = new ArrayList<>();
        if(list != null && list.size()>0){
            list.stream().forEach(post -> {
                Map map = new HashMap();
                map.put("post",post);
                User user = userService.findUserByUserId(post.getUserId());
                map.put("user",user);
                posts.add(map);
            });
        }
        model.addAttribute("posts",posts);
        model.addAttribute("orderMode",orderMode);
        return "index";
    }


    /**
     * 进入 500 错误界面
     *
     * @return
     */
    @GetMapping("/error")
    public String getErrorPage() {
        return "/error/500";
    }

    /**
     * 没有权限访问时的错误界面（也是 404）
     *
     * @return
     */
    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }

}
